package locktest.myredislock.controller;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁测试
 */
@RestController
public class RedisLockDemoController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @CrossOrigin
    @RequestMapping("/redisLock")
    public String redisLock(){
        String Id = UUID.randomUUID().toString();
        //相当于jedis.get("number")
        // Boolean result = stringRedisTemplate.opsForValue().setIfAbsent("lockKey","jiankucun");
        // stringRedisTemplate.expire("lockKey",10, TimeUnit.SECONDS);
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent("lockKey",Id,10,TimeUnit.SECONDS);
        if(!result){
            return "error_code";
        }
        try{
            int number = Integer.parseInt(stringRedisTemplate.opsForValue().get("number"));
            //采用setnx实现分布式锁
            if(number>0){
                int realNumber = number - 1;
                //相当于jedis.set();
                stringRedisTemplate.opsForValue().set("number",realNumber+"");
                System.out.println("减库存成功，剩余："+realNumber);
            }else{
                System.out.println("减库存失败，库存不足");
            }
        }finally {
            if(Id.equals(stringRedisTemplate.opsForValue().get("lockKye"))){
              stringRedisTemplate.delete("lockKey");
            }
        }
        return "end";
    }
}
